<template>
  <div class="patrol-point-container">
    <div class="patrol-header">
      <h2>巡更点位</h2>
      <el-select
          v-model="selectedCommunity"
          placeholder="选择小区"
          @change="loadPoints"
          style="width: 200px; margin-right: 10px;"
      >
        <el-option
            v-for="community in communityList"
            :key="community.id"
            :label="community.name"
            :value="community.id"
        ></el-option>
      </el-select>
      <el-button type="primary" @click="addPoint">
        <Plus /> 添加点位
      </el-button>
    </div>

    <el-table
        :data="points"
        border
        style="width: 100%;"
        v-loading="loading"
    >
      <el-table-column prop="pointName" label="点位名称" width="120" />
      <el-table-column prop="locationNo" label="位置编号" width="100" />
      <el-table-column prop="categoryName" label="分类" width="100" />
      <el-table-column prop="buildingName" label="所属楼宇" width="100" />
      <el-table-column prop="unit" label="单元" width="80" />
      <el-table-column prop="photoRequired" label="拍照要求" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.photoRequired === 1 ? 'success' : 'info'">
            {{ scope.row.photoRequired === 1 ? '需要' : '不需要' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="80">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
            {{ scope.row.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template #default="scope">
          <el-button
              size="small"
              type="primary"
              @click="editPoint(scope.row)"
              style="margin-right: 5px;"
          >
            编辑
          </el-button>
          <el-button size="small" type="danger" @click="deletePoint(scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增/编辑点位弹窗 -->
    <el-dialog
        title="巡更点位信息"
        :visible.sync="dialogVisible"
        width="500px"
    >
      <el-form
          :model="formData"
          ref="formRef"
          label-width="120px"
          :rules="formRules"
      >
        <el-form-item label="点位名称" prop="pointName">
          <el-input v-model="formData.pointName" />
        </el-form-item>
        <el-form-item label="所属社区" prop="communityId">
          <el-select v-model="formData.communityId" placeholder="请选择社区">
            <el-option
                v-for="community in communityList"
                :key="community.id"
                :label="community.name"
                :value="community.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="点位分类" prop="categoryId">
          <el-select v-model="formData.categoryId" placeholder="请选择分类">
            <el-option
                v-for="category in categoryList"
                :key="category.categoryId"
                :label="category.categoryName"
                :value="category.categoryId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="位置编号" prop="locationNo">
          <el-input v-model="formData.locationNo" />
        </el-form-item>
        <el-form-item label="所属楼宇" prop="buildingName">
          <el-input v-model="formData.buildingName" />
        </el-form-item>
        <el-form-item label="单元" prop="unit">
          <el-input v-model="formData.unit" />
        </el-form-item>
        <el-form-item label="经纬度" prop="location">
          <el-input v-model="formData.location" placeholder="格式: 经度,纬度" />
        </el-form-item>
        <el-form-item label="拍照要求" prop="photoRequired">
          <el-switch
              v-model="formData.photoRequired"
              active-value="1"
              inactive-value="0"
              active-text="需要"
              inactive-text="不需要"
          ></el-switch>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
              v-model="formData.status"
              active-value="1"
              inactive-value="0"
              active-text="启用"
              inactive-text="禁用"
          ></el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="savePoint">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import {
  getPointByCommunity,
  addPoint,
  updatePoint,
  deletePoint as deletePointApi
} from '../api/patrolPoint'
import { getCategoryByCommunity } from '../api/patrolCategory'
import {getCommunityList} from "../api/community.js";

export default {
  name: 'PatrolPoint',
  components: {
    Plus
  },
  setup() {
    // 社区列表
    const communityList = ref([])

    // 分类列表
    const categoryList = ref([])

    // 响应式数据
    const selectedCommunity = ref(1)
    const points = ref([])
    const loading = ref(false)
    const dialogVisible = ref(false)
    const isEdit = ref(false)
    const formRef = ref(null)

    // 表单数据
    const formData = reactive({
      pointId: null,
      pointName: '',
      communityId: null,
      categoryId: null,
      locationNo: '',
      buildingName: '',
      unit: '',
      location: '',
      photoRequired: true,
      status: '1'
    })

    // 表单验证规则
    const formRules = reactive({
      pointName: [
        { required: true, message: '请输入点位名称', trigger: 'blur' }
      ],
      communityId: [
        { required: true, message: '请选择所属社区', trigger: 'change' }
      ],
      categoryId: [
        { required: true, message: '请选择点位分类', trigger: 'change' }
      ],
      locationNo: [
        { required: true, message: '请输入位置编号', trigger: 'blur' }
      ],
      location: [
        { required: true, message: '请输入经纬度', trigger: 'blur' },
        {
          pattern: /^\d+\.\d+,\d+\.\d+$/,
          message: '经纬度格式不正确，格式应为: 经度,纬度',
          trigger: 'blur'
        }
      ]
    })

    // 加载分类列表
    const loadCategoryList = async () => {
      try {
        const res = await getCategoryByCommunity(selectedCommunity.value)
        if (res.code === 200) {
          categoryList.value = res.data
        } else {
          ElMessage.error(res.message || '加载分类失败')
        }
      } catch (error) {
        ElMessage.error('网络错误，请稍后重试')
        console.error('加载分类失败:', error)
      }
    }

    // 加载点位数据
    const loadPoints = async () => {
      try {
        loading.value = true;
        console.log("请求参数：", { communityId: selectedCommunity.value }); // 打印请求参数
        let {data:data} = await getPointByCommunity(selectedCommunity.value);
        console.log("接口返回完整数据：", data); // 打印完整返回结果
        console.log("点位数据中的拍照要求：", data.data.map(item => item.photoRequired));
        if (data.code === 0) {
          points.value = data.data;
        } else {
          // 打印具体错误信息
          console.error("接口返回错误：", data.message || "未知错误");
          ElMessage.error(data.message || "加载点位失败");
        }
      } catch (error) {
        // 打印网络错误详情
        console.error("请求失败：", error);
        ElMessage.error("网络错误，请稍后重试");
      } finally {
        loading.value = false;
      }
    };

    // 添加点位
    const addPoint = () => {
      isEdit.value = false
      formData.pointId = null
      formData.pointName = ''
      formData.communityId = selectedCommunity.value
      formData.categoryId = null
      formData.locationNo = ''
      formData.buildingName = ''
      formData.unit = ''
      formData.location = '116.404,39.915' // 默认北京坐标
      formData.photoRequired = true
      formData.status = '1'
      dialogVisible.value = true

      // 加载分类列表
      loadCategoryList()
    }

    // 编辑点位
    const editPoint = (row) => {
      isEdit.value = true
      formData.pointId = row.pointId
      formData.pointName = row.pointName
      formData.communityId = row.communityId
      formData.categoryId = row.categoryId
      formData.locationNo = row.locationNo
      formData.buildingName = row.buildingName
      formData.unit = row.unit
      formData.location = `${row.longitude},${row.latitude}`
      formData.photoRequired = row.photoRequired;
      formData.status = row.status.toString()
      dialogVisible.value = true

      // 加载分类列表
      loadCategoryList()
    }

    // 删除点位
    const deletePoint = async (row) => {
      try {
        await ElMessageBox.confirm(
            `确定要删除点位 "${row.pointName}" 吗？`,
            '提示',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }
        )

        const res = await deletePointApi(row.pointId)
        if (res.code === 200) {
          ElMessage.success('删除成功')
          loadPoints()
        } else {
          ElMessage.error(res.message || '删除失败')
        }
      } catch (error) {
        // 如果是取消操作，不显示错误信息
        if (error !== 'cancel') {
          ElMessage.error('网络错误，请稍后重试')
          console.error('删除失败:', error)
        }
      }
    }

    // 保存点位
    const savePoint = async () => {
      // 表单验证
      formRef.value.validate((valid) => {
        if (!valid) return false

        // 解析经纬度
        const [longitude, latitude] = formData.location.split(',')

        // 准备提交数据
        const submitData = {
          pointId: formData.pointId,
          pointName: formData.pointName,
          communityId: formData.communityId,
          categoryId: formData.categoryId,
          locationNo: formData.locationNo,
          buildingName: formData.buildingName,
          unit: formData.unit,
          longitude: parseFloat(longitude),
          latitude: parseFloat(latitude),
          photoRequired: formData.photoRequired,
          status: parseInt(formData.status)
        }

        const saveMethod = isEdit.value ? updatePoint : addPoint
        const actionName = isEdit.value ? '更新' : '添加'

        saveMethod(submitData)
            .then(res => {
              if (res.code === 200) {
                ElMessage.success(`${actionName}成功`)
                dialogVisible.value = false
                loadPoints()
              } else {
                ElMessage.error(res.message || `${actionName}失败`)
              }
            })
            .catch(error => {
              ElMessage.error('网络错误，请稍后重试')
              console.error(actionName + '失败:', error)
            })
      })
    }
    // 加载社区列表（补充缺失的逻辑）
    const loadCommunityList = async () => {
      try {
        let {data:data} = await getCommunityList(); // 调用获取社区列表的接口
        if (data.code === 0) {
          communityList.value = data.data;
          // 初始选中第一个社区（如果有数据）
          if (communityList.value.length > 0) {
            selectedCommunity.value = communityList.value[0].id;
          }
        }
      } catch (error) {
        console.error("加载社区列表失败：", error);
      }
    };

    // 组件挂载时加载数据
    onMounted(async () => {
      await loadCommunityList(); // 先加载社区
      if (communityList.value.length > 0) {
        loadPoints(); // 社区加载成功后再加载点位
      } else {
        ElMessage.warning("请先配置社区数据");
      }
    });

    return {
      communityList,
      selectedCommunity,
      categoryList,
      points,
      loading,
      dialogVisible,
      formData,
      formRules,
      formRef,
      loadPoints,
      addPoint,
      editPoint,
      deletePoint,
      savePoint
    }
  }
}
</script>

<style scoped>
.patrol-point-container {
  padding: 20px;
}

.patrol-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.patrol-header h2 {
  margin-right: 20px;
}
</style>